
import request from '@/utils/request';
// import { AppGraphQLHost, IdentifyGraphQLHost } from '@root/api/urls';

import { GraphQLClient } from './client';
import { Link } from './link';
import { Operation, FetchResult, QueryOptions, QueryResult, MutationOptions } from './types';
import { RequestMethod } from 'umi-request';
import { AppGraphQLHost } from '@/common/constants';

class Client {
  private link: Link;
//   private identifyLink: Link;
  private graphqlClient: GraphQLClient;
//   private identifyGraphqlClient: GraphQLClient;

  public request = request.options;
  public get = request.get;
  public delete = request.delete;
  public post = request.post;
  public put = request.put;
  public patch = request.patch;

  private requestInstance: RequestMethod;

  constructor() {
    this.requestInstance = request;
    // this.axiosInstance.defaults.baseURL = ApiHost;

    this.get = this.requestInstance.get;
    this.delete = this.requestInstance.delete;
    this.post = this.requestInstance.post;
    this.put = this.requestInstance.put;
    this.patch = this.requestInstance.patch;

    this.link = new Link(
      async (operation: Operation): Promise<FetchResult | null> => {
          //@ts-ignore
        const resp = await this.requestInstance.post(AppGraphQLHost,  { data: operation});
        if (resp ) {
          return resp;
        }

        return null;
      },
    );

    // this.identifyLink = new Link(
    //   async (operation: Operation): Promise<FetchResult | null> => {
    //     const resp = await this.requestInstance.post(IdentifyGraphQLHost, operation);

    //     if (resp && resp.data) {
    //       return resp.data;
    //     }

    //     return null;
    //   },
    // );

    this.graphqlClient = new GraphQLClient({
      link: this.link,
    });

    // this.identifyGraphqlClient = new GraphQLClient({
    //   link: this.identifyLink,
    // });
  }

  async query<T>(options: QueryOptions): Promise<QueryResult<T>> {
    return this.graphqlClient.query<T>(options);
  }

//   async identifyQuery<T>(options: QueryOptions): Promise<QueryResult<T>> {
//     return this.identifyGraphqlClient.query<T>(options);
//   }

  async mutate<T>(options: MutationOptions<T>): Promise<FetchResult<T>> {
    return this.graphqlClient.mutate<T>(options);
  }
}

const client = new Client();

export default client;
